/**
 * 设置控制器 - 管理系统设置、敏感内容过滤和黑名单
 */

const { Setting } = require('../models');
const filterService = require('../services/filterService');
const db = require('../models');

// 黑名单表
const PhoneBlacklist = db.PhoneBlacklist;
const ContentBlacklist = db.ContentBlacklist;

/**
 * 获取所有设置
 */
exports.getAllSettings = async (req, res) => {
  try {
    const settings = await Setting.findAll();
    
    // 转换为键值对象
    const settingsObj = {};
    settings.forEach(setting => {
      try {
        settingsObj[setting.key] = JSON.parse(setting.value);
      } catch (e) {
        settingsObj[setting.key] = setting.value;
      }
    });
    
    res.json(settingsObj);
  } catch (error) {
    console.error('获取设置失败:', error);
    res.status(500).json({ message: '服务器内部错误', error: error.message });
  }
};

/**
 * 获取指定设置
 */
exports.getSettingByKey = async (req, res) => {
  try {
    const { key } = req.params;
    
    const setting = await Setting.findOne({
      where: { key }
    });
    
    if (!setting) {
      return res.status(404).json({ message: '设置不存在' });
    }
    
    // 尝试解析JSON
    try {
      setting.value = JSON.parse(setting.value);
    } catch (e) {
      // 如果解析失败，保持原始字符串
    }
    
    res.json({
      key: setting.key,
      value: setting.value,
      description: setting.description
    });
  } catch (error) {
    console.error('获取设置失败:', error);
    res.status(500).json({ message: '服务器内部错误', error: error.message });
  }
};

/**
 * 更新设置
 */
exports.updateSetting = async (req, res) => {
  try {
    const { key } = req.params;
    const { value, description } = req.body;
    
    // 如果value是对象，则转为JSON字符串
    const storedValue = typeof value === 'object' ? JSON.stringify(value) : value;
    
    const [setting, created] = await Setting.upsert({
      key,
      value: storedValue,
      description,
      updatedBy: req.user.username
    });
    
    res.json({
      message: created ? '设置已创建' : '设置已更新',
      setting: {
        key: setting.key,
        description: setting.description,
        updatedBy: setting.updatedBy,
        updatedAt: setting.updatedAt
      }
    });
  } catch (error) {
    console.error('更新设置失败:', error);
    res.status(500).json({ message: '服务器内部错误', error: error.message });
  }
};

/**
 * 获取敏感内容过滤设置
 */
exports.getSensitiveFilterSettings = async (req, res) => {
  try {
    // 从filterService获取设置
    const settings = filterService.getSettings();
    
    // 确保始终返回有效的设置对象
    if (!settings || Object.keys(settings).length === 0) {
      // 如果filterService返回空设置，则返回默认设置
      const defaultSettings = {
        enableNumberMasking: true,
        numberMaskingPattern: '###****##',
        enableLongNumberDetection: true,
        longNumberThreshold: 8,
        detectCreditCards: true,
        detectPhoneNumbers: true,
        enableImageFiltering: true,
        imageFilteringLevel: 'medium',
        storeOriginalContent: true,
        notifyAdminOnDetection: true,
        numberPatterns: [],
        sensitiveKeywords: []
      };
      
      return res.json(defaultSettings);
    }
    
    res.json(settings);
  } catch (error) {
    console.error('获取敏感内容过滤设置失败:', error);
    // 出错时返回基本设置，确保前端能正常工作
    res.json({
      enableNumberMasking: true,
      numberMaskingPattern: '###****##',
      enableLongNumberDetection: true,
      longNumberThreshold: 8,
      detectCreditCards: true,
      detectPhoneNumbers: true,
      enableImageFiltering: true,
      imageFilteringLevel: 'medium',
      storeOriginalContent: true,
      notifyAdminOnDetection: true,
      numberPatterns: [],
      sensitiveKeywords: []
    });
  }
};

/**
 * 更新敏感内容过滤设置
 */
exports.updateSensitiveFilterSettings = async (req, res) => {
  try {
    const settings = req.body;
    
    // 防止恶意修改设置
    delete settings.initialize;
    delete settings.getSettings;
    delete settings.updateSettings;
    
    let result;
    try {
      result = await filterService.updateSettings(settings);
    } catch (updateError) {
      console.error('更新敏感内容过滤设置出错:', updateError);
      result = { success: false, error: updateError.message };
    }
    
    if (result.success) {
      res.json({ message: '敏感内容过滤设置已更新', settings: filterService.getSettings() });
    } else {
      // 尝试直接保存到内存中，即使数据库保存失败
      try {
        const currentSettings = filterService.getSettings();
        const mergedSettings = { ...currentSettings, ...settings };
        // 这里只是把设置保存在内存中
        res.json({ 
          message: '敏感内容过滤设置已更新（仅内存）', 
          warning: '数据库保存失败，设置将在服务重启后丢失',
          settings: mergedSettings 
        });
      } catch (memoryError) {
        res.status(400).json({ message: '更新敏感内容过滤设置失败', error: result.error });
      }
    }
  } catch (error) {
    console.error('更新敏感内容过滤设置失败:', error);
    res.status(500).json({ message: '服务器内部错误', error: error.message });
  }
};

/**
 * 重置敏感内容过滤设置
 */
exports.resetSensitiveFilterSettings = async (req, res) => {
  try {
    // 初始化过滤服务会重置为默认值
    await filterService.initialize();
    
    res.json({ message: '敏感内容过滤设置已重置', settings: filterService.getSettings() });
  } catch (error) {
    console.error('重置敏感内容过滤设置失败:', error);
    res.status(500).json({ message: '服务器内部错误', error: error.message });
  }
};

/**
 * 获取电话黑名单
 */
exports.getPhoneBlacklist = async (req, res) => {
  try {
    const blacklist = await PhoneBlacklist.findAll({
      order: [['createdAt', 'DESC']]
    });
    
    res.json(blacklist);
  } catch (error) {
    console.error('获取电话黑名单失败:', error);
    res.status(500).json({ message: '服务器内部错误', error: error.message });
  }
};

/**
 * 获取内容黑名单
 */
exports.getContentBlacklist = async (req, res) => {
  try {
    const blacklist = await ContentBlacklist.findAll({
      order: [['createdAt', 'DESC']]
    });
    
    res.json(blacklist);
  } catch (error) {
    console.error('获取内容黑名单失败:', error);
    res.status(500).json({ message: '服务器内部错误', error: error.message });
  }
};

/**
 * 添加电话黑名单
 */
exports.addPhoneBlacklist = async (req, res) => {
  try {
    const { phoneNumber, reason } = req.body;
    
    if (!phoneNumber) {
      return res.status(400).json({ message: '电话号码是必须的' });
    }
    
    const blacklistItem = await PhoneBlacklist.create({
      phoneNumber,
      reason: reason || '管理员添加',
      status: 'active',
      createdBy: req.user.username
    });
    
    res.status(201).json({
      message: '电话黑名单项已添加',
      blacklistItem
    });
  } catch (error) {
    console.error('添加电话黑名单失败:', error);
    res.status(500).json({ message: '服务器内部错误', error: error.message });
  }
};

/**
 * 添加内容黑名单
 */
exports.addContentBlacklist = async (req, res) => {
  try {
    const { content, type, action, reason } = req.body;
    
    if (!content) {
      return res.status(400).json({ message: '内容是必须的' });
    }
    
    // 验证正则表达式是否有效
    if (type === 'regex') {
      try {
        new RegExp(content);
      } catch (e) {
        return res.status(400).json({ message: '无效的正则表达式', error: e.message });
      }
    }
    
    const blacklistItem = await ContentBlacklist.create({
      content,
      type: type || 'keyword',
      action: action || 'flag',
      reason: reason || '管理员添加',
      status: 'active',
      createdBy: req.user.username
    });
    
    res.status(201).json({
      message: '内容黑名单项已添加',
      blacklistItem
    });
  } catch (error) {
    console.error('添加内容黑名单失败:', error);
    res.status(500).json({ message: '服务器内部错误', error: error.message });
  }
};

/**
 * 删除电话黑名单
 */
exports.deletePhoneBlacklist = async (req, res) => {
  try {
    const { id } = req.params;
    
    const blacklistItem = await PhoneBlacklist.findByPk(id);
    
    if (!blacklistItem) {
      return res.status(404).json({ message: '黑名单项不存在' });
    }
    
    await blacklistItem.destroy();
    
    res.json({ message: '电话黑名单项已删除' });
  } catch (error) {
    console.error('删除电话黑名单失败:', error);
    res.status(500).json({ message: '服务器内部错误', error: error.message });
  }
};

/**
 * 删除内容黑名单
 */
exports.deleteContentBlacklist = async (req, res) => {
  try {
    const { id } = req.params;
    
    const blacklistItem = await ContentBlacklist.findByPk(id);
    
    if (!blacklistItem) {
      return res.status(404).json({ message: '黑名单项不存在' });
    }
    
    await blacklistItem.destroy();
    
    res.json({ message: '内容黑名单项已删除' });
  } catch (error) {
    console.error('删除内容黑名单失败:', error);
    res.status(500).json({ message: '服务器内部错误', error: error.message });
  }
};

/**
 * 获取黑名单设置
 */
exports.getBlacklist = async (req, res) => {
  try {
    // 获取电话黑名单
    const phoneBlacklist = await db.PhoneBlacklist.findAll({
      order: [['createdAt', 'DESC']]
    });
    
    // 获取内容黑名单
    const contentBlacklist = await db.ContentBlacklist.findAll({
      order: [['createdAt', 'DESC']]
    });
    
    res.json({
      phones: phoneBlacklist,
      contents: contentBlacklist
    });
  } catch (error) {
    console.error('获取黑名单设置失败:', error);
    res.status(500).json({ message: '获取黑名单设置失败', error: error.message });
  }
};

/**
 * 添加黑名单项
 */
exports.addBlacklistItem = async (req, res) => {
  try {
    const { phoneNumber, content, type, action, reason } = req.body;
    
    if (phoneNumber) {
      // 添加电话黑名单
      const newItem = await db.PhoneBlacklist.create({
        phoneNumber,
        reason,
        createdBy: req.user ? req.user.username : 'system',
        status: 'active'
      });
      
      res.status(201).json(newItem);
    } else if (content) {
      // 添加内容黑名单
      const newItem = await db.ContentBlacklist.create({
        content,
        type: type || 'keyword',
        action: action || 'flag',
        reason,
        status: 'active',
        createdBy: req.user ? req.user.username : 'system'
      });
      
      res.status(201).json(newItem);
    } else {
      res.status(400).json({ message: '请提供电话号码或内容关键词' });
    }
  } catch (error) {
    console.error('添加黑名单项失败:', error);
    res.status(500).json({ message: '添加黑名单项失败', error: error.message });
  }
};

/**
 * 删除电话黑名单项
 */
exports.deletePhoneBlacklistItem = async (req, res) => {
  try {
    const { id } = req.params;
    
    const item = await db.PhoneBlacklist.findByPk(id);
    
    if (!item) {
      return res.status(404).json({ message: '黑名单项不存在' });
    }
    
    await item.destroy();
    
    res.json({ success: true, message: '电话黑名单项已删除' });
  } catch (error) {
    console.error('删除黑名单项失败:', error);
    res.status(500).json({ message: '删除黑名单项失败', error: error.message });
  }
};

/**
 * 删除内容黑名单项
 */
exports.deleteContentBlacklistItem = async (req, res) => {
  try {
    const { id } = req.params;
    
    const item = await db.ContentBlacklist.findByPk(id);
    
    if (!item) {
      return res.status(404).json({ message: '黑名单项不存在' });
    }
    
    await item.destroy();
    
    res.json({ success: true, message: '内容黑名单项已删除' });
  } catch (error) {
    console.error('删除黑名单项失败:', error);
    res.status(500).json({ message: '删除黑名单项失败', error: error.message });
  }
}; 